//
//  CurlTest.cpp
//  GRE
//
//  Created by Kutlak Roman on 20/10/2011.
//  Copyright (c) 2011 University of Aberdeen. All rights reserved.
//

#include <iostream>

#include <gtest/gtest.h>

#include "Curl.h"
#include "Settings.h"
using namespace kutlak::roman::gre;

using std::string;
using std::endl;
using std::cout;
using std::cerr;

TEST(Curl, Constructor) {
    Curl* curl = NULL;
    try {
        curl = new Curl();
    } catch (string s) {
        cerr << "Exception: " << s << endl;
    }
    
    EXPECT_NE((Curl*)0, curl);

    if (curl) {
        EXPECT_EQ("", curl->ErrorMessage());
        delete curl;
    }
}

TEST(Curl, Request) {
    Curl curl;
    
    // trivial case
    try
    {
        curl.Request("");
        EXPECT_EQ(CURLE_OK, curl.ErrorCode());
        EXPECT_EQ(true, curl.Result().empty());
        EXPECT_EQ(string::npos, curl.Result().find("html"));
        EXPECT_EQ(CURLE_OK, curl.ErrorCode());
        EXPECT_EQ("", curl.ErrorMessage());
        EXPECT_EQ(0, Curl::Requests());
    }
    catch (std::runtime_error& e)
    {
        cerr << e.what() << '\n';
    }
    
    // correct query
    try
    {
        curl.Request("http://www.kutlak.me.uk/");
        EXPECT_EQ(CURLE_OK, curl.ErrorCode());
        EXPECT_EQ(false, curl.Result().empty());
        EXPECT_NE(string::npos, curl.Result().find("html"));
        EXPECT_EQ(CURLE_OK, curl.ErrorCode());
        EXPECT_EQ("", curl.ErrorMessage());
        EXPECT_EQ(1, Curl::Requests());
    }
    catch (std::runtime_error& e)
    {
        // the above request should not throw
        EXPECT_EQ(true, false);
        cerr << e.what() << '\n';
    }
    
    // incorrect protocol
    try
    {
        // this should throw
        curl.Request("afp://www.kutlak.me.uk/");
        EXPECT_EQ(true, false);
    }
    catch (std::runtime_error& e)
    {
        EXPECT_EQ(CURLE_UNSUPPORTED_PROTOCOL, curl.ErrorCode());
        EXPECT_EQ(true, curl.Result().empty());
        EXPECT_EQ(string::npos, curl.Result().find("html"));
        EXPECT_EQ(CURLE_UNSUPPORTED_PROTOCOL, curl.ErrorCode());
        EXPECT_NE("", curl.ErrorMessage());
        EXPECT_EQ(1, Curl::Requests());
        cerr << e.what() << '\n';
    }
    
    
    // bad url -  no host
    // proxy can return an actual page displaying the error
    try
    {
        if (Settings::Instance().GetSetting("UseProxy") != "true") {
            // this should throw
            curl.Request("http://kutl&k/");
            EXPECT_EQ(true, false);
        }
    }
    catch (std::runtime_error& e)
    {
        EXPECT_EQ(CURLE_COULDNT_RESOLVE_HOST, curl.ErrorCode());
        EXPECT_EQ(true, curl.Result().empty());
        EXPECT_EQ(string::npos, curl.Result().find("html"));
        EXPECT_EQ(CURLE_COULDNT_RESOLVE_HOST, curl.ErrorCode());
        EXPECT_NE("", curl.ErrorMessage());
        EXPECT_EQ(1, Curl::Requests());
        cerr << e.what() << '\n';
    }
    
}


